const jwt = require('jsonwebtoken');
module.exports = class extends baseLogic {
    constructor() {
        super();
    }

    static init() {
        return new this();
    }

    /**
     *
     * @param FindFilterModel 查询条件
     * @param curPage 当前页
     * @param pageSize 分页尺寸
     * @param sort 排序
     * @param moduleId 当前模块ID
     * @param userInfo 用户信息
     * @returns {Promise<void>}
     */
    async getItems(FindFilterModel, curPage, pageSize, sort, moduleId, userInfo) {
        let self = this;
        let Result = {};
        Result.CurPage = curPage;
        Result.PageSize = pageSize;
        let FindFilter = await this.func.degree.getDegree(moduleId, userInfo, {
            createBy: 'UserID',
            orgId: 'UserOrgStructID',
            partnersId: 'UserPartnersID',
            areaCode: 'UserAreaCode'
        });
        FindFilter.UserIsSuper = 0;
        FindFilter.UserIsDel = 0;


        if (FindFilterModel.userIds.length > 0) {
            FindFilter.UserID = FindFilterModel.userIds;
        }
        if (FindFilterModel.UserRealName) {
            FindFilter['$or'] = [{
                "UserPingYin": {
                    '$like': FindFilterModel.UserRealName + '%'
                }
            }, {
                "UserRealName": {
                    '$like': FindFilterModel.UserRealName + '%'
                }
            }];
        }

        if (FindFilterModel.UserMobilePhone) {
            FindFilter.UserMobilePhone = {
                '$like': '%' + FindFilterModel.UserMobilePhone + '%'
            };
        }

        if (FindFilterModel.UserJobNum) {
            FindFilter.UserJobNum = {
                '$like': '%' + FindFilterModel.UserJobNum + '%'
            };
        }

        if (FindFilterModel.UserCreatetime) {
            FindFilter.UserCreatetime = {
                '$between': FindFilterModel.UserCreatetime.split(',')
            };
        }

        if (FindFilterModel.UserRule) {
            FindFilter.UserRule = FindFilterModel.UserRule.split(',');
        }

        let partnersInfo = null;
        if (!isNaN(FindFilterModel.UserOrgStructID)) {
            partnersInfo = await this.func.orgStruct.GetParentModelByType(FindFilterModel.UserOrgStructID, '001');
            let ChildrensID_array = await this.func.orgStruct.getChildrensID(FindFilterModel.UserOrgStructID);
            ChildrensID_array.push(Number(FindFilterModel.UserOrgStructID));
            FindFilter.UserOrgStructID = ChildrensID_array;
        }



        //-----获取当前企业下的角色
        let _filter = {};
        if (partnersInfo) {
            _filter.RuleOrgID = partnersInfo.OS_ID;
        }
        let iframe_rule = await this.DB.iframe_rule.Access.findAll({
            where: _filter,
            raw: true
        });
        Result.IframeRule = iframe_rule;
        //------------获取当前用户的组织结构---------------
        //Result.OrgStruct =await this.func.orgStruct.GetTreeData(FindFilterModel.PartnersID, userInfo.UserOrgStructID);
        Result.OrgStruct = await this.func.orgStruct.GetUserOrgStructTreeData(moduleId, userInfo); //根据各自的数据可视化程度 获取用户可见的组织结构的树形结构数据
        let data = await this.DB.iframe_user.Access.findAndCountAll({
            where: FindFilter,
            order: [
                sort.split('|')
            ],
            offset: (curPage - 1) * pageSize,
            limit: pageSize,
            raw: true
        });
        Result.RsCount = data.count;
        Result.DataList = JSON.parse(JSON.stringify(data.rows));
        Result.DataList.map(async (item) => {
            let curOrg = await this.func.orgStruct.GetOrgStuctItem(item.UserOrgStructID);
            let DictModel = await this.func.partnersDict.GetDictItem(item.UserPartnersID, "UserType", item.UserType);
            item.UserTypeName = DictModel ? DictModel.zd_Name : '';
            item.UserOrgStructName = curOrg ? curOrg.OS_Name : '';

            item.UserRuleName = '';
            let UserRules = item.UserRule.split(',');
            UserRules.forEach(function (ur) {
                if (ur !== '') {
                    iframe_rule.forEach(function (rule) {
                        if (rule.RuleID === Number(ur)) {
                            item.UserRuleName += rule.RuleName + " ";
                        }
                    })
                }
            });

        });

        return Result;

    }

    async getItem(uid) {
        let model = await this.DB.iframe_user.Access.findOne({
            where: {
                UserId: uid
            },
            raw: true
        });
        return model;
    }

    async insertOrUpdate(_model) {
        let model = {};
        if (_model.UserID > 0) {
            model = await this.getItem(_model.UserID);
            if (!model) {
                return false;
            }
        } else {
            model.UserID = this.webTools.myuuid.createUUID();
            model.UserPwd = this.webTools.common.GetMD5('123456');
            model.UserAccessToken = this.webTools.common.UUID(32, 16);
            model.UserLoginTime = model.UserCreatetime = this.moment().unix();
            model.UserIsSuper = 0;
            model.UserIsDel = 0;
        }
        model.UserMobilePhone = _model.UserMobilePhone;
        model.UserRealName = _model.UserRealName;
        model.UserPingYin = _model.UserPingYin;
        model.UserJobNum = _model.UserJobNum;
        model.UserRule = _model.UserRule;
        model.UserOrgStructID = _model.UserOrgStructID;
        model.UserPartnersID = _model.UserPartnersID;
        model.UserAreaCode = _model.UserAreaCode || '';
        model.UserType = _model.UserType || '';
        model.UserHeaderImg = _model.UserHeaderImg || '/res/images/header/default.png';
        if (_model.UserID > 0) {
            model = await this.DB.iframe_user.Access.update(model, {
                where: {
                    UserID: _model.UserID
                }
            })
        } else {
            model = await this.DB.iframe_user.Access.create(model);
        }

        if (model) {
            return true;
        }
        return false;
    }

    async del(keys) {
        await this.DB.iframe_user.Access.update({
            UserIsDel: 1
        }, {
            where: {
                UserID: keys
            }
        });
        return true;
    }

    async resetPwd(uid, pwd) {
        if (!pwd || pwd === '') {
            pwd = "123456";
        }
        await this.DB.iframe_user.Access.update({
            UserPwd: this.webTools.common.GetMD5(pwd).toLowerCase()
        }, {
            where: {
                UserID: uid
            }
        });
        return true;
    }


    /**
     * 管理员登录
     * @param {*} param0
     */
    async login({
        UserName,
        Pwd,
        PartnersId,
        Type,
        Sign
    }) {
        let ret = new this.webTools.CallBackData();
        let UserPartnersSign = Sign;
        let queryFilter = {
            UserIsDel: 0,
            UserPartnersID: PartnersId
        };

        if (Type == 1) {
            queryFilter.UserMobilePhone = UserName;
        } else {
            queryFilter.UserName = UserName;
        }
        let UserModel = await this.DB.iframe_user.Access.find({
            where: queryFilter
        });

        if (UserModel) {

            //---------
            if (UserModel.UserPwd.toLowerCase() === this.webTools.common.GetMD5(Pwd).toLowerCase()) {

                let endTime = this.moment().subtract(1000, 'M').unix();
                if (UserModel.UserAccessToken === '' || UserModel.UserLoginTime < endTime) { //一个月过期
                    UserModel.UserAccessToken = this.webTools.common.UUID(32, 16);
                }
                UserModel.UserLoginTime = this.moment().unix();
                await UserModel.save();
                let UserInfo = await this.func.curUserInfo.getUserInfo(UserModel.UserID);

                let authToken = jwt.sign(UserInfo, this.config.authKeyWord);
                UserInfo.AuthToken = authToken;


                let ModuleItems = await this.func.systemModule.getUserModule(UserModel.UserRule, UserModel.UserPartnersID);
                if (ModuleItems && ModuleItems.length > 0) {
                    let FirstModule = {};
                    for (let i = 0; i < ModuleItems.length; i++) {
                        if (ModuleItems[i].ParentID === 0) {
                            FirstModule = ModuleItems[i];
                            break;
                        }
                    }

                    let TargetModule = this.func.systemModule.FindTargetModule(ModuleItems, FirstModule.ModuleID);
                    if (TargetModule) {
                        //let UserModelJson =await this.func.curUserInfo.getUserInfo(UserModel.UserID);
                        UserInfo.UserPartnersSign = UserPartnersSign;
                        ret.Data.UserInfo = UserInfo;
                        ret.Data.TargetUrl = TargetModule.URL;
                        ret.Data.UserModules = ModuleItems;
                        ret.Result = 1;
                    } else {
                        ret.Result = 0;
                        ret.Msg = '系统权限配置错误';

                    }

                } else {
                    ret.Result = 0;
                    ret.Msg = '无权限';

                }

            } else {
                ret.Msg = '密码错误';
            }
        } else {
            ret.Msg = '用户不存在';
        }

        return ret;
    }

    /**
     * 获取当前登录用户的信息
     * @param {*} UserInfo
     */
    async getLoginUserInfo(UserInfo) {
        if (UserInfo) {
            delete UserInfo.UserPwd;
            if (UserInfo.UserIsSuper == 1) {
                UserInfo.UserRuleName = "系统超级管理员";
            } else {
                UserInfo.UserRuleName = '';
                let _UserRule = UserInfo.UserRule.split(',');
                for (let i = 0; i < _UserRule.length; i++) {
                    let item = _UserRule[i];
                    if (item != '') {
                        let _item = await this.DB.iframe_rule.Access.findById(item);
                        if (_item) {
                            UserInfo.UserRuleName += _item.RuleName + ",";
                        }
                    }
                }

                if (UserInfo.UserRuleName.indexOf(',') > -1) UserInfo.UserRuleName = UserInfo.UserRuleName.substr(0, UserInfo.UserRuleName.length - 1);
            };
            if (UserInfo.UserOrgStructID == 0) {
                UserInfo.UserOrgStructName = "";
            } else {
                let ParentsNames = [];
                ParentsNames = ParentsNames.concat(await this.func.orgStruct.GetParentsName(UserInfo.UserOrgStructID));
                UserInfo.UserOrgStructName = ParentsNames.join('-');
            }
            return UserInfo;
        }
    }
};